package com.d3works.apps.base.web;

import com.d3works.apps.base.callable.ControllerCallableTool;
import com.d3works.apps.base.db.Batch;
import com.d3works.apps.base.db.MailBatch;
import com.d3works.apps.base.db.repo.MailBatchRepository;
import com.d3works.apps.base.exceptions.BaseExceptionMessage;
import com.d3works.apps.base.service.batch.MailBatchService;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;

@Singleton
public class MailBatchController {

  public void remindTimesheet(ActionRequest request, ActionResponse response) {

    try {
      MailBatch mailBatch = request.getContext().asType(MailBatch.class);

      MailBatchService mailBatchService = Beans.get(MailBatchService.class);
      mailBatchService.setBatchModel(Beans.get(MailBatchRepository.class).find(mailBatch.getId()));
      ControllerCallableTool<Batch> batchControllerCallableTool = new ControllerCallableTool<>();
      Batch batch = batchControllerCallableTool.runInSeparateThread(mailBatchService, response);

      if (batch != null) {
        response.setInfo(batch.getComments());
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    } finally {
      response.setReload(true);
    }
  }

  public void remindTimesheetGeneral(ActionRequest request, ActionResponse response) {
    try {

      MailBatch mailBatch =
          Beans.get(MailBatchRepository.class)
              .findByCode(MailBatchRepository.CODE_BATCH_EMAIL_TIME_SHEET);
      if (mailBatch != null) {

        MailBatchService mailBatchService = Beans.get(MailBatchService.class);
        mailBatchService.setBatchModel(mailBatch);
        ControllerCallableTool<Batch> batchControllerCallableTool = new ControllerCallableTool<>();
        Batch batch = batchControllerCallableTool.runInSeparateThread(mailBatchService, response);

        if (batch != null) {
          response.setInfo(batch.getComments());
        }
      } else {
        throw new D3worksException(
            TraceBackRepository.CATEGORY_INCONSISTENCY,
            I18n.get(BaseExceptionMessage.BASE_BATCH_2),
            MailBatchRepository.CODE_BATCH_EMAIL_TIME_SHEET);
      }

    } catch (Exception e) {
      TraceBackService.trace(response, e);
    } finally {
      response.setReload(true);
    }
  }
}
